
<?php defined('IN_NWIDC') or exit('Access Invalid!');?>
<script src="<?php echo RESOURCE_SITE_URL;?>/js/common_select.js"></script>

<?php
$m = Model('setting');
$config = $m->getListSetting();
@include dirname(BASE_PATH) . '/shop/templates/' . $config['template_name'] . '/fix_cart.php';
?>

<script>
    var iframe;
    function faker_post(){
        var post_info = '<?php echo base64_encode(json_encode($_POST));?>';
        if(iframe){
            iframe.remove();
        }
        layer.load()
        iframe = $('<iframe>').css('display','none').attr({
            src : location.href + '&super_post=' + post_info + '&address_id=' + $('#edit_reciver').attr('default_id')

        }).appendTo('body');
    }
</script>
<?php
?>
<form method="post" id="order_form" name="order_form" action="index.php">
<input type='hidden' name='order_split' value='0' />
<?php
    $m = Model('setting');
    $config = $m->getListSetting();

?>
<script>

    var split_limit = '<?php echo $config['split_limit']?>';
    var tax_start = '<?php echo $config['tax_start_else']?>';
    var tax_top = '<?php echo $config['tax_start']?>';

    var store_cart_list = <?php echo json_encode($output['store_cart_list']);?>;
    if(split_limit == ''){
        split_limit = 0;
    }
    var arr_count = 0;


    function clone(myObj){
        if(typeof(myObj) != 'object') return myObj;
        if(myObj == null) return myObj;
        var myNewObj = new Object();
        for(var i in myObj)
        myNewObj[i] = clone(myObj[i]);
        return myNewObj;
    }

    function count_obj(obj){
        var i = 0;
        for(var key in obj){
            ++i;
        }

        return i;
    }


    function get_split_order(goods,just_tax){
        var item = {};
        var orders = [];
        var limit = 0;
        var simple_order = {};
        for(var i = 0; i < goods.length; i++){
            var g = goods[i];
            var n = g.goods_num;
            var lock = false;

            if(g.open_tax == 0){
                simple_order[g.goods_id] = g;
                continue;
            }

            if(just_tax){
                item[g.goods_id] = g;
            }else{
                //凡是单个保税商品的税费超过设定的，这些就单独成一个订单
                if(g.tax > tax_start){
                    item[g.goods_id] = g;
                    orders.push(item);
                    item = {}
                    limit = 0;
                    continue;
                }
                while(g.goods_num){
                    //如果仍然未到
                    if(limit + g.tax <= split_limit){
                        limit += g.tax;
                        g.goods_num--;
                        if(!item[g.goods_id]){
                            item[g.goods_id] = clone(g);
                            item[g.goods_id].goods_num = 1;
                        }
                        else{
                            item[g.goods_id].goods_num++;
                        }

                    }
                    //如果可能越界
                    else{
                        if(count_obj(item) == 0){
                            g.goods_num--;
                            item[g.goods_id] = clone(g);
                            item[g.goods_id].goods_num = 1;
                            orders.push(item);
                            limit = 0;
                            item = {}
                            continue;
                        }
                        orders.push(item);
                        item = {};
                        limit = 0;
                    }
                }
            }

        }
        if(count_obj(simple_order)){
            orders.push(simple_order);
        }

        if(count_obj(item)){
            orders.push(item);
        }



        orders = orders.sort(function(a,b){
            for(var i in a){
                if(a[i].open_tax == 0){
                    return 1;
                }
            }
            return 0;
        });

        return orders;

    }

    function fix_double(num){
        var str = num.toFixed(3).toString();
        return str.substring(0,str.length - 1);
    }

    function order_split(just_tax){
        //得到拆分差值
        var orders = [];
        var count = 0;
        var items = $('[name*=pay_message]');
        for(var i in store_cart_list){
            //对每一个商家分别处理
            var item = {}
            var goods = store_cart_list[i];
            for(var j = 0; j < goods.length; j++){
                if(goods[j].goods_storage == 0){
                    layer.msg('您的订单中存在库存不足的商品，无法下单！',function(){
                        history.go(-1);
                    });
                    return;
                }
            }
            var orders = get_split_order(goods,just_tax);
            // console.log(orders);
            //更新视图
            var item = null;
            items.each(function(){
                if(this.name == "pay_message[" + i + "]"){
                    item = $(this).closest('tr').siblings('.shop-list');
                }
            });
            for(var j = 0; j < orders.length; j++){
                var simple = false;
                var tax = 0;
                var total = 0;
                for(var n in orders[j]){
                    if(orders[j][n].tax > 0){
                        tax += orders[j][n].tax * orders[j][n].goods_num;
                    }
                    total += orders[j][n].goods_total;
                    if(orders[j][n].open_tax == 0){
                        simple = true;
                        break;
                    }
                }

                //if ignore tax
                // console.log('thisis' + tax + ' '  + tax_start+ ' ' + total+ ' ' + tax_top);
                if(!(tax > tax_start || total > tax_top)){
                    for(var n in orders[j]){
                        if(orders[j][n].tax > 0){
                            orders[j][n].goods_total -= orders[j][n].tax * orders[j][n].goods_num;
                            orders[j][n].goods_price -= orders[j][n].tax;
                            orders[j][n].tax = 0;
                        }
                    }
                    //更正订单价格
                    var goods_amount_box = $('#eachStoreGoodsTotal_' + i);
                    goods_amount_box.html(fix_double(goods_amount_box.html() - tax));
                    var total_amount_box = $('[nc_type=eachStoreTotal][store_id=' + i + ']');
                    total_amount_box.html(fix_double(total_amount_box.html() - tax));
                    //total_total_amount
                    var t_amount = $('#orderTotal');
                    t_amount.html(fix_double(t_amount.html() - tax));
                    tax = 0;
                }

                var newrow = $('<tr><td colspan="20">订单'+(-(-j-1)) + (simple ? ' <b>(国内完税订单)</b> ' : '    <b>(税金：￥' + tax + ')</b>') +'</td></tr>').insertBefore(item.eq(0));
                for(var n in orders[j]){
                    var goods = orders[j][n];
                    var clone = item.eq(0).clone();
                    //干掉这个
                    clone.find('td').eq(0).empty();
                    //连接
                    clone.find("td").eq(1).find('a').attr('href','/shop/index.php?act=goods&op=index&goods_id=' + goods.goods_id);
                    //img
                    clone.find("td").eq(1).find('img').attr('alt','').attr('src',goods.goods_image_url);
                    //link and name
                    clone.find('td').eq(2).find('a').attr('href','/shop/index.php?act=goods&op=index&goods_id=' + goods.goods_id).text(goods.goods_name);
                    //single price(source)
                    clone.find('td').eq(3).find('em').text(goods.source_price);
                    //proxy price
                    clone.find('td').eq(4).find('em').text(goods.goods_proxy);
                    //tax
                    clone.find('td').eq(5).find('em').text(goods.open_tax ? goods.tax : '无');
                    // cosnole.lo
                    //num
                    clone.find('td').eq(6).text(goods.goods_num);
                    //total
                    clone.find('td').eq(7).find('em').removeAttr('id').text(fix_double(goods.goods_price * goods.goods_num));

                    clone.insertBefore(item.eq(0));

               }



            }


            item.hide();

            count++;

        }


    }

    function start_split(flag){
        if(!flag){
            flag = false;
        }
        var timer = setInterval(function(){
            if($('.ncc-msg-textarea').length){
                order_split(flag);
                clearInterval(timer);
            }
        });
    }

</script>
<?php
    if($config['order_split'] == 1){
        if($config['manual_split'] == 1){
?>
<script>
    //计算每个店铺的tax
    (function(){

        var flag = false;
        for(var i in store_cart_list){
            var tax = 0;
            for(var j = 0; j < store_cart_list[i].length; j++){
                if(store_cart_list[i][j].tax > 0){
                    tax += store_cart_list[i][j].tax * store_cart_list[i][j].goods_num;
                }
            }
            if(tax > split_limit){
                flag = true;
                break;
            }
        }


        if(flag){
            layer.confirm("您的订单行邮税过多，系统可能会将订单拆分，确认拆分吗？",{title:"提示"},function(index){
                $('[name=order_split]').val(1);
                layer.close(index);
                start_split();
            },function(){
                start_split(true);
            });
        }
        else{
            start_split(true);
        }

    });
</script>
<?php
        }
        else{
?>
<script>
    (function(){
        var flag = false;
        for(var i in store_cart_list){
            var tax = 0;
            for(var j = 0; j < store_cart_list[i].length; j++){
                if(store_cart_list[i][j].tax > 0){
                    tax += store_cart_list[i][j].tax * store_cart_list[i][j].goods_num;
                }
            }
            if(tax > split_limit){
                flag = true;
                break;
            }
        }
        if(flag){
            $('[name=order_split]').val(1);
            start_split();
        }
        else{
            start_split(true)
        }
    });
</script>
<?php
        }
?>
<?php
    }
?>
<?php include template('buy/buy_fcode');?>
<div class="ncc-main">
  <div class="ncc-title">
    <h3><?php echo $lang['cart_index_ensure_info'];?></h3>
    <h5>请仔细核对填写收货、发票等信息，以确保物流快递及时准确投递。</h5>
  </div>
    <?php include template('buy/buy_address');?>
    <?php include template('buy/buy_payment');?>
    <?php include template('buy/buy_invoice');?>
    <?php include template('buy/buy_goods_list');?>
    <?php include template('buy/buy_amount');?>
    <input value="buy" type="hidden" name="act">
    <input value="buy_step2" type="hidden" name="op">
    <!-- 来源于购物车标志 -->
    <input value="<?php echo $output['ifcart'];?>" type="hidden" name="ifcart">

    <!-- offline/online -->
    <input value="online" name="pay_name" id="pay_name" type="hidden">

    <!-- 是否保存增值税发票判断标志 -->
    <input value="<?php echo $output['vat_hash'];?>" name="vat_hash" type="hidden">

    <!-- 收货地址ID -->
    <input value="<?php echo $output['address_info']['address_id'];?>" name="address_id" id="address_id" type="hidden">

    <!-- 城市ID(运费) -->
    <input value="" name="buy_city_id" id="buy_city_id" type="hidden">

    <!-- 记录所选地区是否支持货到付款 第一个前端JS判断 第二个后端PHP判断 -->
    <input value="" id="allow_offpay" name="allow_offpay" type="hidden">
    <input value="" id="allow_offpay_batch" name="allow_offpay_batch" type="hidden">
    <input value="" id="offpay_hash" name="offpay_hash" type="hidden">
    <input value="" id="offpay_hash_batch" name="offpay_hash_batch" type="hidden">

    <!-- 默认使用的发票 -->
    <input value="<?php echo $output['inv_info']['inv_id'];?>" name="invoice_id" id="invoice_id" type="hidden">
    <input value="<?php echo getReferer();?>" name="ref_url" type="hidden">
</div>
</form>
<script type="text/javascript">
var SUBMIT_FORM = true;
//计算总运费和每个店铺小计
function calcOrder() {
    var allTotal = 0;
    $('em[nc_type="eachStoreTotal"]').each(function(){
        store_id = $(this).attr('store_id');
        var eachTotal = 0;
        if ($('#eachStoreFreight_'+store_id).length > 0) {
        	eachTotal += parseFloat($('#eachStoreFreight_'+store_id).html());
	    }
        if ($('#eachStoreGoodsTotal_'+store_id).length > 0) {
        	eachTotal += parseFloat($('#eachStoreGoodsTotal_'+store_id).html());
	    }
        if ($('#eachStoreManSong_'+store_id).length > 0) {
        	eachTotal += parseFloat($('#eachStoreManSong_'+store_id).html());
	    }
        if ($('#eachStoreVoucher_'+store_id).length > 0) {
        	eachTotal += parseFloat($('#eachStoreVoucher_'+store_id).html());
        }
        $(this).html(number_format(eachTotal,2));
        allTotal += eachTotal;
    });
    $('#orderTotal').html(number_format(allTotal,2));

    // window.cal_total = true;
    //如果这是个iframe,那么取出刷新的表单
    if(window.parent != window){
        var $$ = window.parent.jQuery;
        $('.ncc-store-account').each(function(){
            var store_id = $(this).closest('tbody').attr('store_id');
            $$('tbody[store_id=' + store_id + ']').find('.' + this.classList).html(this.innerHTML);
        })
        $$('#orderTotal').html($('#orderTotal').html());
        parent.layer.closeAll();
    }
}
$(function(){
    $.ajaxSetup({
        async : false
    });
    $('select[nctype="voucher"]').on('change',function(){
        if ($(this).val() == '') {
        	$('#eachStoreVoucher_'+items[1]).html('-0.00');
        } else {
            var items = $(this).val().split('|');
            $('#eachStoreVoucher_'+items[1]).html('-'+number_format(items[2],2));
        }
        calcOrder();
    });

    <?php if (!empty($output['available_pd_amount']) || !empty($output['available_rcb_amount'])) { ?>
    function showPaySubmit() {
        if ($('input[name="pd_pay"]').attr('checked') || $('input[name="rcb_pay"]').attr('checked')) {
        	$('#pay-password').val('');
        	$('#password_callback').val('');
        	$('#pd_password').show();
        } else {
        	$('#pd_password').hide();
        }
    }

    $('#pd_pay_submit').on('click',function(){
        if ($('#pay-password').val() == '') {
        	showDialog('请输入支付密码', 'error','','','','','','','','',2);return false;
        }
        $('#password_callback').val('');
		$.get("index.php?act=buy&op=check_pd_pwd", {'password':$('#pay-password').val()}, function(data){
            if (data == '1') {
            	$('#password_callback').val('1');
            	$('#pd_password').hide();
            } else {
            	$('#pay-password').val('');
            	showDialog('支付密码码错误', 'error','','','','','','','','',2);
            }
        });
    });
    <?php } ?>

    <?php if (!empty($output['available_rcb_amount'])) { ?>
    $('input[name="rcb_pay"]').on('change',function(){
    	showPaySubmit();
    	if ($(this).attr('checked') && !$('input[name="pd_pay"]').attr('checked')) {
        	if (<?php echo $output['available_rcb_amount']?> >= parseFloat($('#orderTotal').html())) {
            	$('input[name="pd_pay"]').attr('checked',false).attr('disabled',true);
        	}
    	} else {
    		$('input[name="pd_pay"]').attr('disabled',false);
    	}
    });
    <?php } ?>

    <?php if (!empty($output['available_pd_amount'])) { ?>
    $('input[name="pd_pay"]').on('change',function(){
    	showPaySubmit();
    	if ($(this).attr('checked') && !$('input[name="rcb_pay"]').attr('checked')) {
        	if (<?php echo $output['available_pd_amount']?> >= parseFloat($('#orderTotal').html())) {
            	$('input[name="rcb_pay"]').attr('checked',false).attr('disabled',true);
        	}
    	} else {
    		$('input[name="rcb_pay"]').attr('disabled',false);
    	}
    });
    <?php } ?>

});
function disableOtherEdit(showText){
	$('a[nc_type="buy_edit"]').each(function(){
	    if ($(this).css('display') != 'none'){
			$(this).after('<font color="#B0B0B0">' + showText + '</font>');
		    $(this).hide();
	    }
	});
	disableSubmitOrder();
}
function ableOtherEdit(){
	$('a[nc_type="buy_edit"]').show().next('font').remove();
	ableSubmitOrder();

}
function ableSubmitOrder(){
	$('#submitOrder').on('click',function(){submitNext()}).css('cursor','').addClass('ncc-btn-acidblue');
}
function disableSubmitOrder(){
	$('#submitOrder').unbind('click').css('cursor','not-allowed').removeClass('ncc-btn-acidblue');
}
</script>
